package com.google.firebase.quickstart.database.fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.firebase.ui.common.ChangeEventType;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.DemoApplication;
import com.google.firebase.quickstart.database.MainActivity;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.SignInActivity;
import com.google.firebase.quickstart.database.common.data.model.Dialog;
import com.google.firebase.quickstart.database.common.data.model.User;
import com.google.firebase.quickstart.database.custom.MDialogsList;
import com.google.firebase.quickstart.database.custom.holder.CustomHolderMessagesActivity;
import com.google.firebase.quickstart.database.viewholder.ChatViewHolder;
import com.squareup.picasso.Picasso;
import com.stfalcon.chatkit.commons.ImageLoader;
import com.stfalcon.chatkit.dialogs.DialogsListAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class ChatsListFragment extends Fragment {
    private static final String TAG = "ChatsListFragment";

    // [START define_database_reference]
    private DatabaseReference mDatabase;
    // [END define_database_reference]

    private FirebaseRecyclerAdapter<Dialog, ChatViewHolder> mAdapter;
    //    private RecyclerView mRecycler;
    private LinearLayoutManager mManager;
    private ImageLoader imageLoader;
    private MDialogsList dialogsList;

    public ChatsListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_chats, container, false);
        imageLoader = new ImageLoader() {
            @Override
            public void loadImage(ImageView imageView, String url) {
                Picasso.with(getContext()).load(url).into(imageView);
            }
        };
        // [START create_database_reference]
        mDatabase = FirebaseDatabase.getInstance().getReference();
        // [END create_database_reference]
        dialogsList = rootView.findViewById(R.id.dialogsList);

//        mRecycler = rootView.findViewById(R.id.messages_list);
//        mRecycler.setHasFixedSize(true);

        return rootView;
    }

    int unReadCount;
    List<Dialog> dialogs = new ArrayList<>();
    NotificationManager notificationManager;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Set up Layout Manager, reverse layout
//        mManager = new LinearLayoutManager(getActivity());
//        mManager.setReverseLayout(true);
//        mManager.setStackFromEnd(true);
//        mRecycler.setLayoutManager(mManager);

        notificationManager = (NotificationManager) getActivity().getSystemService(getContext().NOTIFICATION_SERVICE);
        // Set up FirebaseRecyclerAdapter with the Query
        Query postsQuery = getQuery(mDatabase);

        final FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Dialog>()
                .setQuery(postsQuery, Dialog.class)
                .build();

        mAdapter = new FirebaseRecyclerAdapter<Dialog, ChatViewHolder>(options) {

            @Override
            public void onChildChanged(@NonNull ChangeEventType type, @NonNull DataSnapshot snapshot, int newIndex, int oldIndex) {
                Dialog dialog = snapshot.getValue(Dialog.class);
                switch (type) {
                    case ADDED:
                        dialogs.add(dialog);
                        unReadCount += dialog.unreadCount;
                        notifyItemInserted(newIndex);
                        break;
                    case CHANGED:
                        unReadCount += dialog.unreadCount - dialogs.get(newIndex).unreadCount;
                        dialogs.get(newIndex).unreadCount = dialog.unreadCount;
                        notifyItemChanged(newIndex);
                        break;
                    case REMOVED:
                        unReadCount -= dialog.unreadCount;
                        dialogs.remove(newIndex);
                        notifyItemRemoved(newIndex);
                        break;
                    case MOVED:
                        if (oldIndex != newIndex) {
                            Dialog dialog1 = dialogs.get(newIndex);
                            Dialog dialog2 = dialogs.get(oldIndex);
                            dialogs.set(oldIndex, dialog1);
                            dialogs.set(newIndex, dialog2);
                        }
                        notifyItemMoved(oldIndex, newIndex);
                        break;
                    default:
                        throw new IllegalStateException("Incomplete case statement");
                }
                if (unReadCount > 0) {
                    if (MainActivity.mainActivity.unreadBubble != null) {
                        MainActivity.mainActivity.unreadBubble.setVisibility(View.VISIBLE);
                        MainActivity.mainActivity.unreadBubble.setText("" + unReadCount);
                    }
                } else {
                    if (MainActivity.mainActivity.unreadBubble != null) {
                        MainActivity.mainActivity.unreadBubble.setVisibility(View.GONE);
                    }
                }
                sendNotify(options);
                DemoApplication.unReadMsg = unReadCount;
            }

            @Override
            public ChatViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
                ChatViewHolder chatViewHolder = new ChatViewHolder(inflater.inflate(R.layout.item_custom_dialog_view_holder, viewGroup, false));
                chatViewHolder.setImageLoader(imageLoader);
                chatViewHolder.setDialogStyle(dialogsList.getDialogStyle());

                return chatViewHolder;
            }

            @Override
            protected void onBindViewHolder(ChatViewHolder viewHolder, int position, final Dialog model) {
                final DatabaseReference postRef = getRef(position);
                viewHolder.setOnDialogClickListener(new DialogsListAdapter.OnDialogClickListener<Dialog>() {
                    @Override
                    public void onDialogClick(Dialog dialog) {

                        postRef.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                Dialog dialog = dataSnapshot.getValue(Dialog.class);
                                final User user = new User(postRef.getKey(), dialog.getTitle(), dialog.getAvatar(), true);

                                DatabaseReference chats = mDatabase.child("chats").child(DemoApplication.mUser.getId()).child(user.getId());
                                chats.addListenerForSingleValueEvent(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
//                                        String messageKey;
                                        long deleteTime = 0;
                                        Dialog dialog = dataSnapshot.getValue(Dialog.class);
                                        if (dialog != null && dialog.getChatId() != null) {
//                                            messageKey = dialog.getChatId();
                                            deleteTime = dialog.deleteTimestamp;
                                        } else {
//                                            messageKey = FirebaseDatabase.getInstance().getReference()
//                                                    .child("messages").push().getKey();
                                        }
                                        Intent intent = new Intent(getActivity(), CustomHolderMessagesActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable(CustomHolderMessagesActivity.EXTRA_USER, user);
//                                        intent.putExtra(CustomHolderMessagesActivity.EXTRA_MESSAGE_KEY, messageKey);
                                        intent.putExtra(CustomHolderMessagesActivity.EXTRA_DELETETIME_KEY, deleteTime);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {
                                    }
                                });

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                // Getting Post failed, log a message
                                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
                            }
                        });
                    }
                });
                // Set click listener for the whole post view
                viewHolder.onBind(model);
            }
        };
        dialogsList.setAdapter(mAdapter);

        if (mAdapter != null) {
            mAdapter.startListening();
        }
    }

    public static String CHANNEL_ID = "channel id";

    void sendNotify(FirebaseRecyclerOptions options) {
        if (options.getSnapshots().size() == dialogs.size()) {
            if (DemoApplication.unReadMsg < unReadCount && unReadCount > 0) {
                //发起本地通知
                PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(getActivity(), SignInActivity.class).putExtra("chat", true), 0);

                Notification notification = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "测试name", NotificationManager.IMPORTANCE_HIGH);
                    mChannel.enableLights(true);
                    mChannel.setLightColor(Color.RED);
                    mChannel.enableVibration(true);
//                    mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    notificationManager.createNotificationChannel(mChannel);
                    notification = new Notification.Builder(getActivity(), CHANNEL_ID)
                            .setDefaults(Notification.DEFAULT_ALL)
                            .setSmallIcon(R.drawable.jpush_notification_icon)//设置小图标
                            .setContentTitle("TestChat")
                            .setContentText("你有" + unReadCount + "条新消息")
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();
                } else {
                    notification = new Notification.Builder(getActivity())
                            .setDefaults(Notification.DEFAULT_ALL)
                            .setSmallIcon(R.drawable.jpush_notification_icon)//设置小图标
                            .setContentTitle("TestChat")
                            .setContentText("你有" + unReadCount + "条新消息")
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();
                }
                notificationManager.notify(0, notification);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy() {
        if (mAdapter != null) {
            dialogs.clear();
            unReadCount = 0;
            mAdapter.stopListening();
        }
        super.onDestroy();
    }

    public String getUid() {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    public abstract Query getQuery(DatabaseReference databaseReference);

}
